<template>
    <div>
        <!-- opened Dialog 打开动画结束时的回调 -->
        <el-dialog @opened="opened" :title="info.title" :visible.sync="info.isShow" :before-close="close">
            <el-form :model="form" :rules="rules" ref="form1">

                <!-- 一级分类 -->
                <el-form-item label="一级分类" :label-width="formLabelWidth" prop="first_cateid">
                    <el-select v-model="form.first_cateid" @change="changeCate(false)" placeholder="请选择一级分类">
                        <el-option v-for="item in cate" :key="item.id" :label="item.catename" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <!-- 二级分类 -->
                <el-form-item label="二级分类" :label-width="formLabelWidth" prop="second_cateid">
                    <el-select v-model="form.second_cateid" placeholder="请选择二级分类">
                        <el-option v-for="item in cateArr" :key="item.id" :label="item.catename"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <!-- 商品名称 -->
                <el-form-item label="商品名称" :label-width="formLabelWidth" prop="goodsname">
                    <el-input v-model="form.goodsname" autocomplete="off"></el-input>
                </el-form-item>

                <!-- 价格 -->
                <el-form-item label="价格" :label-width="formLabelWidth">
                    <el-input v-model="form.price" autocomplete="off"></el-input>
                </el-form-item>

                <!-- 市场价格 -->
                <el-form-item label="市场价格" :label-width="formLabelWidth">
                    <el-input v-model="form.market_price" autocomplete="off"></el-input>
                </el-form-item>

                <!-- on-preview	点击文件列表中已上传的文件时的钩子
                        on-remove	文件列表移除文件时的钩子
                        file-list 上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}]
                        auto-upload  是否在选取文件后立即进行上传
                -->
                <el-form-item v-show="form.pid !== 0" label="图片" :label-width="formLabelWidth">
                    <el-upload action="#" list-type="picture-card" :on-change="change"
                        :on-preview="handlePictureCardPreview" :file-list="fileList" :auto-upload="false">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-form-item>

                <!-- 商品规格 -->
                <el-form-item label="商品规格" :label-width="formLabelWidth">
                    <el-select v-model="form.specsid" placeholder="请选择商品规格" @change="changeSpecs">
                        <el-option v-for="item in specs" :key="item.id" :label="item.specsname"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <!-- 规格属性 -->
                <el-form-item label="规格属性" :label-width="formLabelWidth">
                    <el-select v-model="form.specsattr" placeholder="请选择规格属性" multiple>
                        <el-option v-for="item in specsArr" :key="item" :label="item" :value="item"></el-option>
                    </el-select>
                </el-form-item>

                <!-- 是否新品 -->
                <el-form-item label="是否新品" :label-width="formLabelWidth">
                    <el-radio v-model="form.isnew" :label="1">是</el-radio>
                    <el-radio v-model="form.isnew" :label="2">否</el-radio>
                </el-form-item>

                <!-- 是否热卖 -->
                <el-form-item label="是否热卖" :label-width="formLabelWidth">
                    <el-radio v-model="form.ishot" :label="1">是</el-radio>
                    <el-radio v-model="form.ishot" :label="2">否</el-radio>
                </el-form-item>

                <!-- 状态 -->
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="form.status" active-color="#13ce66" inactive-color="#ccc" :active-value="1"
                        :inactive-value="2">
                    </el-switch>
                </el-form-item>
                <!-- 商品描述 -->
                <el-form-item label="商品描述" :label-width="formLabelWidth">
                    <div id="main"></div>
                </el-form-item>


            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取消</el-button>
                <el-button v-if="info.isAdd" type="primary" @click="confirm">确 定</el-button>
                <el-button v-else type="primary" @click="amend">修 改</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import { successAlert } from '@/utils/alert'
import { goodsAdd, goodsInfo, goodsEdit } from '@/request/api'
import E from 'wangeditor'
export default {
    data() {
        return {
            formLabelWidth: '120px',
            form: {
                first_cateid: '',  //一级分类编号
                second_cateid: '',  //二级分类编号
                goodsname: '',  //商品名称
                price: '',  //商品价格
                market_price: '',  //市场价格
                img: '',  //商品图片（文件）
                description: '',  //商品描述
                specsid: '',  //商品规格编号
                specsattr: [],  //商品规格属性
                isnew: 1,  //是否新品     1-是 2-否
                ishot: 1,  //是否热卖推荐 1-是 2-否
                status: 1  //状态1正常2禁用
            },
            //校验正则
            rules: {
                first_cateid: [
                    { required: true, message: '请选择一级分类', trigger: 'change' }
                ],
                second_cateid: [
                    { required: true, message: '请选择二级分类', trigger: 'change' }
                ],
                goodsname: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
                ]
            },
            //图片上传
            dialogImageUrl: '', //预览图片地址
            dialogVisible: false,   //图片预览是否展示
            fileList: [],  // 图片的数据数组
            cateArr: [],// 二级分类
            specsArr: [], //规格属性
            //文本编辑器
            editor: null
        }

    },
    props: ['info'],
    methods: {
        ...mapActions({
            requestCate: 'cate/listActions',
            requestSpecs: 'specs/listActions',
            requestGoods: 'goods/listActions',
            requestCount: 'goods/countActions',
        }),
        //数据回显
        getDetail(id) {
            // console.log(id);
            goodsInfo({ id }).then(res => {
                // console.log(res);
                if (res.code === 200) {
                    this.form = res.list;
                    // console.log(this.form);
                    this.form.id = id
                    //图片
                    this.fileList = this.form.img ? [{ url: 'http://localhost:3000' + this.form.img }] : []
                    //规格属性
                    this.form.specsattr = this.form.specsattr.split(',')
                    // console.log(this.form.specsattr);
                    //二级分类商品
                    this.changeCate(true)

                }
            })
        },
        //修改
        amend() {
            this.form.description = this.editor.txt.html()
            goodsEdit(this.form).then(res => {
                // console.log(res);
                if (res.code === 200) {
                    //消息提示
                    successAlert(res.msg)
                    //取消弹窗
                    this.cancel()
                    //更新列表
                    this.requestGoods()
                }
            })
        },
        close() {
            this.cancel()
        },
        //取消
        cancel() {
            this.info.isShow = false
            this.form = {
                first_cateid: '',  //一级分类编号
                second_cateid: '',  //二级分类编号
                goodsname: '',  //商品名称
                price: '',  //商品价格
                market_price: '',  //市场价格
                img: '',  //商品图片（文件）
                description: '',  //商品描述
                specsid: '',  //商品规格编号
                specsattr: [],  //商品规格属性
                isnew: 1,  //是否新品     1-是 2-否
                ishot: 1,  //是否热卖推荐 1-是 2-否
                status: 1  //状态1正常2禁用
            }
            this.$refs.form1.resetFields()
            this.fileList = []
            //html方法中不加内容获取，加上是设置文本内容
            this.editor.txt.html('')
        },
        // 获取二级分类
        changeCate(n) {
            // console.log(n);
            // console.log(this.form.first_cateid);
            //findIndex寻找它得下标
            if (!n) {
                this.form.second_cateid = ''
            }

            let index = this.cate.findIndex((item) => item.id == this.form.first_cateid);
            // console.log(this.form.first_cateid);
            // console.log(this.cate);
            // console.log(index);
            // if (this.cate[index].children) {
            this.cateArr = this.cate[index].children
            // }
        },
        //获取规格属性
        changeSpecs() {
            // console.log(this.form.specsid);
            this.form.specsattr = ''
            let index = this.specs.findIndex((item) => item.id == this.form.specsid)
            // console.log(index);
            this.specsArr = this.specs[index].attrs
        },
        //确定
        confirm() {
            this.$refs.form1.validate((val) => {
                if (!val) {
                    return
                }
                this.form.description = this.editor.txt.html()
                // console.log(this.form);
                goodsAdd(this.form).then(res => {
                    // console.log(res);
                    if (res.code === 200) {
                        //消息提示
                        successAlert(res.msg)
                        //取消弹窗
                        this.cancel()
                        //更新列表
                        this.requestGoods()
                        this.requestCount()
                    }
                })

            })
        },
        opened() {
            if (!this.editor) {
                //创建富文本
                this.editor = new E('#main')
                //创建编辑器
                this.editor.create()
            }

            //数据回显
            setTimeout(() => {
                this.editor.txt.html(this.form.description);
            }, 400);

        },
        //点击预览图片
        handlePictureCardPreview() {
            this.dialogVisible = true
        },
        //文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
        change(file, fileList) {
            this.dialogImageUrl = file.url
            this.form.img = file.raw
        }
    },
    mounted() {
        //发起商品分类
        this.requestCate()
        //发起规格属性
        this.requestSpecs()
    },
    watch: {},
    computed: {
        ...mapGetters({
            cate: 'cate/list',
            specs: 'specs/list'
        })
    },
    filters: {},
    components: {}
}
</script>
<style scoped></style>